package com.gxar.quick.ar.server.base.async.identify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxar.quick.ar.server.base.common.properties.IdentifyProperties;
import com.gxar.quick.ar.server.base.sdk.IdentifySDK;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/4/15 14:52
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IdentifyAsync {

    private final IdentifySDK identifySdk;
    private final IdentifyProperties identifyProperties;

    @Async("identifyAsyncThread")
    public CompletableFuture<String> predict(String v1, Long userId, String image, Boolean multiResult) {
        try {
            String result = identifySdk.predictIdentify(v1, userId, 0L, image, multiResult);
            if (result.contains("message") && identifyProperties.getEnableLog()) {
                log.info("识别失败, 用户ID：{}, 图片：{}", userId, image);
            }
            return CompletableFuture.completedFuture(result);
        } catch (Exception e) {
            log.info("识别异常:{}", e.getMessage(), e);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", e.getMessage());
            return CompletableFuture.completedFuture(JSON.toJSONString(jsonObject));
        }
    }

    @Async("identifyAsyncThread")
    public CompletableFuture<String> test(int i, Long userId, String image, Boolean multiResult) {
        log.info("========线程========:{}", Thread.currentThread().getName());
        if (i == 2) {
            log.info("========线程成功========:{}", Thread.currentThread().getName());
            return CompletableFuture.completedFuture("success");
        } else {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        log.info("========线程结束========:{}", Thread.currentThread().getName());
        return CompletableFuture.completedFuture("message");
    }

}
